package com.sunagy.demand.front.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunagy.demand.front.VO.CustomerUserBindVo;
import com.sunagy.demand.front.VO.ResultVO;
import com.sunagy.demand.front.config.WXConfig;
import com.sunagy.demand.front.dataobject.CustomerAuthToken;
import com.sunagy.demand.front.dto.CustomerUserDto;
import com.sunagy.demand.front.enums.BuzEnum;
import com.sunagy.demand.front.exception.BuzException;
import com.sunagy.demand.front.service.CustomerAuthTokenService;
import com.sunagy.demand.front.service.CustomerUserInfoService;
import com.sunagy.demand.front.service.CustomerUserService;
import com.sunagy.demand.front.service.SmsService;
import com.sunagy.demand.front.utils.ResultVOUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * desc：微信登录，用户自动注册
 * author：三餘無夢生
 * date：2018/4/19
 * time：下午1:38
 */
@Slf4j
@RestController
@RequestMapping("/wx")
@Api(value = "客户端微信登录", description = "各种微信平台的登录接口")
public class WXLoginController {

    @Autowired
    private WXConfig wxConfig;

    @Autowired
    protected WxMpService wxMpService;

    @Autowired
    protected WxMaService wxMaService;

    @Autowired
    protected CustomerAuthTokenService customerAuthTokenService;

    @Autowired
    protected CustomerUserService customerUserService;

    @Autowired
    protected CustomerUserInfoService customerUserInfoService;

    @Autowired
    private SmsService smsService;

    @ApiOperation(value = "微信公众号登录", notes = "微信公众号直接登陆并注册用户，通过code获得基本用户信息详情请见: http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "java.lang.String", name = "code", value = "微信授权返回的code", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "java.lang.String", name = "state", value = "state参数", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "java.lang.String", name = "lang", value = "语言（zh_CN, zh_TW, en）", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "java.lang.String", name = "redirectUrl", value = "登录之后成功跳转的链接地址，需要encode", required = false, paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "接口异常")
    })
    @RequestMapping(value = "/mp/login", method = RequestMethod.GET)
    public void wxRegister(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "code", required = true) String code,
                           @RequestParam(value = "state", required = false) String state,
                           @RequestParam(value = "lang", required = false) String lang,
                           @RequestParam(value = "redirectUrl", required = false) String redirectUrl
    ) {
        redirectUrl = redirectUrl == null ? wxConfig.getMpRedirectUrl() : redirectUrl;
        WxMpOAuth2AccessToken accessToken;
        WxMpUser wxMpUser;
        try {
            accessToken = this.wxMpService.oauth2getAccessToken(code);
            log.info("accessToken: {}", accessToken);
            wxMpUser = this.wxMpService.getUserService()
                    .userInfo(accessToken.getOpenId(), lang);
            log.info("OpenId: {}", wxMpUser.getOpenId());
        } catch (WxErrorException e) {
            log.info("WxErrorException: {}", e.getError().toString());
        }
    }

    @ApiOperation(value = "微信小程序登录", notes = "微信小程序直接登陆并注册用户，通过code获得基本用户信息详情请见: http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "java.lang.String", name = "code", value = "微信授权返回的code", required = true, paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 500, message = "接口异常")
    })
    @RequestMapping(value = "/ma/login", method = RequestMethod.GET)
    public ResultVO<Map<String,String>> wxRegister(HttpServletRequest request, HttpServletResponse response,
                                                @RequestParam(value = "code", required = false) String code) {
        WxMaJscode2SessionResult wxMaJscode2SessionResult;
        CustomerAuthToken customerAuthToken;
        CustomerUserDto customerUserDto = new CustomerUserDto();
        try {
            wxMaJscode2SessionResult = wxMaService.jsCode2SessionInfo(code);
            log.info("wxMaJscode2SessionResult: {}", wxMaJscode2SessionResult);
            String openid = wxMaJscode2SessionResult.getOpenid();
            String token = customerAuthTokenService.authWXMaOpenid(openid);
            Map<String,String> map = new HashMap<>();
            map.put("token",token);
            map.put("openid",openid);
            return ResultVOUtil.success(map);
        } catch (WxErrorException e) {
            log.info("WxErrorException: {}", e.getError().toString());
            throw new BuzException(BuzEnum.WECHAT_PLATFORM_ERROR);
        }
    }

    @ApiOperation(value = "微信小程序用户绑定", notes = "已经注册了微信信息但是没有绑定帐号")
    @ApiResponses({
            @ApiResponse(code = 500, message = "接口异常")
    })
    @RequestMapping(value = "/ma/bind", method = RequestMethod.POST)
    public ResultVO<Map<String,String>> wxRegister(HttpServletRequest request, HttpServletResponse response,@RequestBody CustomerUserBindVo customerUserBindVo) {
        smsService.check(customerUserBindVo.getPhone(),customerUserBindVo.getVerifyCode());
        CustomerAuthToken customerAuthToken = customerAuthTokenService.bindMaOpenid(customerUserBindVo);
        String token = customerAuthToken.getToken();
        Map<String,String> map = new HashMap<>();
        map.put("token",token);
        return ResultVOUtil.success(map);
    }


    /**
     * 解密用户敏感数据获取用户信息
     *
     * @author zhy
     * @param sessionKey 数据进行加密签名的密钥
     * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
     * @param iv 加密算法的初始向量
     * @return
     */
    public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidParameterSpecException e) {
            log.error(e.getMessage(), e);
        } catch (IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        } catch (BadPaddingException e) {
            log.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidKeyException e) {
            log.error(e.getMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            log.error(e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


}
